<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Parcela
 *
 * @author gilmario
 */

namespace App\Models;

use SON\DB\Table;

class Parcela extends Table {

    protected $table = 'parcela';

    public function adiciona($conta, $valor) {
        try {
            $nparcela = $this->geraCodigo($conta);
            $this->db->beginTransaction();
            $query = "INSERT INTO {$this->table} values ({$nparcela},{$conta},{$valor}, now() ) ";
            $this->db->query($query);
            $this->db->commit();
        } catch (Exception $ex) {
            $this->db->roolback();
        }
    }

    public function exclui($conta, $parcela) {
        try {
            $this->db->beginTransaction();
            $query = "DELETE FROM {$this->table} WHERE parcela={$parcela} AND conta ={$conta} ";
            $this->db->query($query);
            $this->db->commit();
        } catch (Exception $ex) {
            $this->db->roolback();
        }
    }

    public function excluiTodas($conta) {
        try {
            $this->db->beginTransaction();
            $query = "DELETE FROM {$this->table} WHERE conta ={$conta} ";
            $this->db->query($query);
            $this->db->commit();
        } catch (Exception $ex) {
            $this->db->roolback();
        }
    }

    public function geraCodigo($conta) {
        $query = "SELECT COUNT(parcela) + 1 as codigo FROM {$this->table} WHERE conta={$conta} ";
        $row = $this->db->query($query);
        $rs = $row->fetch();
        return $rs['codigo'];
    }

    public function valorPago($conta) {
        $query = "SELECT SUM(valor) AS TOTAL FROM {$this->table} WHERE conta={$conta} ";
        $row = $this->db->query($query);
        $rs = $row->fetch();
        return $rs['TOTAL'];
    }

    protected function create() {
        try {
            $this->db->beginTransaction();
            $query = "CREATE TABLE IF NOT EXISTS {$this->table}(parcela INTEGER NOT NULL , conta integer not null, valor double, data_baixa datetime, foreign key (conta) references conta(id), primary key (parcela, conta) ) ENGINE MYISAM";
            $this->db->query($query);
            $this->db->commit();
        } catch (Exception $ex) {
            echo $ex;
            $this->db->roolBack();
        }
    }

}
